import re
from collections import OrderedDict

from rest_framework import response
from rest_framework.mixins import UpdateModelMixin
from rest_framework.response import Response

from .models import Problem, Label, Answer, ProblemLabelRelation, ChildAnswer, UsreProblemLikesRelation
from .serializers import DiscussionSerializer, ProblemLabelSerializer, AnswerSerializer, ChildAnswerSerializer, \
    UsreProblemLikesRelationSerializer
from rest_framework.generics import ListAPIView, RetrieveUpdateAPIView, CreateAPIView, RetrieveUpdateDestroyAPIView, \
    GenericAPIView, RetrieveAPIView


class DiscussionAPIView(ListAPIView, UpdateModelMixin, CreateAPIView):
    """首页问题表"""
    queryset = Problem.objects.all()
    serializer_class = DiscussionSerializer


class ProblemLabelAPIView(ListAPIView):
    """首页标签部分表"""
    queryset = Label.objects.all()
    serializer_class = ProblemLabelSerializer


class ProblemDataAPIView(RetrieveUpdateAPIView):
    """详情内容部分"""

    queryset = Problem.objects.all()
    serializer_class = DiscussionSerializer


class AnswerDataAPIView(ListAPIView):
    """详情评论部分"""

    queryset = Answer.objects.all()
    serializer_class = AnswerSerializer

    # def get(self, requset, *args, **kwargs):
    #     problem＿id = self.kwargs['pk']
    #
    #
    #
    #     return queryset

    def post(self, request, *args, **kwargs):
        data = request.data['content']
        print(data)
        Answer.objects.create(problem＿id=self.kwargs['pk'], answer_content=data, answer_author_id=1)
        return Response('ok')
        # print(type(data))
        # return Response(data)


class SonDataAPIView(CreateAPIView):
    """详情评论部分"""

    # queryset = ChildAnswer.objects.all()
    # serializer_class = ChildAnswerSerializer
    def get_serializer(self, *args, **kwargs):
        pass

    def post(self, request, *args, **kwargs):
        answer_id = request.data['answer']
        child_author_id = request.data['child_author']
        content = request.data['child_content']

        ChildAnswer.objects.create(answer_id=answer_id, child_author_id=child_author_id, child_content=content)

        return Response({"message": 'ok'})


class ProblemLikeAPIView(RetrieveUpdateDestroyAPIView, CreateAPIView):
    serializer_class = UsreProblemLikesRelationSerializer

    def get_object(self, *args, **kwargs):
        problem_id = self.request.query_params['problem_id']
        user_id = self.request.query_params['user_id']

        queryset = UsreProblemLikesRelation.objects.get(Problem_id=problem_id, User_id=user_id)

        return queryset

    def delete(self, request, *args, **kwargs):
        problem_id = request.data['params'].get('problem_id')
        user_id = request.data['params'].get('user_id')
        UsreProblemLikesRelation.objects.get(Problem_id=problem_id, User＿id=user_id).delete()
        return Response({"message": 'ok'})

    def post(self, request, *args, **kwargs):
        problem_id = request.data['params'].get('problem_id')
        user_id = request.data['params'].get('user_id')
        print(type(user_id))
        print(type(problem_id))

        # UsreProblemLikesRelation.objects.create(Problem_id=problem_id, User_id=user_id)
        UsreProblemLikesRelation.objects.create(Problem_id=problem_id, User＿id=user_id)
        return Response({"message": 'ok'})


class UpdataLikeAPIView(RetrieveUpdateAPIView, CreateAPIView):
    def put(self, request, *args, **kwargs):
        problem_id = request.query_params['problem_id']
        awesome = request.query_params['num']
        problem = Problem.objects.get(id=problem_id)
        problem.awesome = awesome
        problem.save()

        return Response({"message": 'ok'})


class SidebarAPIView(ListAPIView):
    queryset = Answer.objects.all()
    serializer_class = AnswerSerializer

    def get(self, requset, *args, **kwargs):
        data = super().get(requset, args, kwargs)
        problem＿id = self.kwargs['pk']
        pro = Problem.objects.get(id=problem＿id)
        labels = pro.label_set.all()
        sim_pros = []
        _ = 4
        for item in labels:
            # qa_set = QaNavigation.objects.filter(~Q(qa_id=pk), navigation_id=item['id'])
            pro_set = item.hanswer.all()
            if not len(pro_set):
                continue
            for i in pro_set:
                if len(pro_set) >= 4:
                    sim_pros.append({"id": i.id, "sim_name": i.title, "comment": 0,
                                     "status": 0})
                    if len(sim_pros) == 4:
                        break
                    continue
                if _ - len(sim_pros) >= 0:
                    sim_pros.append({"id": i.id, "sim_name": i.title, "comment": 0,
                                     "status": 0})
                    _ -= len(sim_pros)
                else:
                    sim_pros.append({"id": i.id, "sim_name": i.title, "comment": 0,
                                     "status": 0})
                    if len(sim_pros) == 4:
                        break
            if len(pro_set) == 4:
                break

        data.data.append({'sim_pros': sim_pros})
        return data


class CreateProbelmAPIView(CreateAPIView):
    def post(self, request, *args, **kwargs):
        user_id = request.data['user_id']
        title = request.data['title']
        content = request.data['content']
        labels = request.data['labels']

        # if len(labels) > 2:
        if re.match(r'^[\u0391-\uFFE5]+$', labels):
            return Response({"message": "标签请分割"})
        # if re.search(r',', labels):
        #     if re.search(r';', labels):
        #         content = re.sub(r';', ',', labels)
        #     labels_list = content.split(',')
        # if re.search(r';', content):
        #     labels_list = content.split(';')
        # if re.match(r'[a-z]+', labels):
        #     labels_list.append(labels)
        # else:
        #     return Response({"message": "格式错误"})

        labels_list = labels.split(",")
        qa_obj = Problem.objects.create(title=title, content=content, author_id=user_id)
        for label_name in labels_list:
            try:
                na_obj = Label.objects.get(label_name=label_name)
            except Label.DoesNotExist:
                na_obj = Label.objects.create(label_name=label_name, label_describe=1)
                ProblemLabelRelation.objects.create(Problem_id=qa_obj.id, Label_id=na_obj.id)
            except Exception:
                return Response({"message": "服务器异常"})
        return Response({"message": "发表成功"})


class GetUserProblemAPIView(ListAPIView):

    def get(self, request, *args, **kwargs):
        print(self.kwargs['pk'])
        queryset = Problem.objects.filter(author_id=self.kwargs['pk'])
        data = DiscussionSerializer(queryset, many=True).data
        print(data)
        return Response(data)


class GetUserCommentAPIView(ListAPIView):

    def get(self, request, *args, **kwargs):
        queryset = Answer.objects.filter(answer_author_id=self.kwargs['pk'])
        data = AnswerSerializer(queryset, many=True).data
        print(data)
        return Response(data)